import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
    state: {//存放状态
        //  购物车数组 
        // [
        //   {
        //     选中状态，自己去添加
        //     图片地址，后端给
        //     商品名称，后端给
        //     商品价格，后端给
        //     商品数量，自己去添加
        //     商品id   后端给
        //   } 
        // ]
        cartList: uni.getStorageSync("cartList") || [],
        storageAddress: uni.getStorageSync("storageAddress"),
        token: ''
    },
    getters: {
        // 获取收货地址  data
        address(state) {
            if (state.storageAddress && (Date.now() - state.storageAddress.time <= 1000 * 60 * 5)) {
                // 有缓存 而且没有过期
                return state.storageAddress.data;
            }
        },

        /// 用户选中的商品数组
        checkedCartList(state) {
            return state.cartList.filter(goods => goods.checked);
        },

        // 全选按钮的设置
        isAllChecked(state, getters) {
            return (
                state.cartList.length && state.cartList.every((goods) => goods.checked)
            );
        },

        // 计算商品的总金额
        totalPrice(state, getters) {
            return getters.checkedCartList.reduce((sum, goods) => sum += goods.goods_price * goods.num, 0);
        },

        // 计算商品总个数
        totalCount(state, getters) {
            return getters.checkedCartList.reduce((sum, goods) => sum += goods.num, 0);
        },
    },
    // 修改state mutations
    mutations: {
        // 添加收货地址
        setAddress(state, address) {
            state.storageAddress = { data: address, time: Date.now() };
            // 存一份到缓存中
            uni.setStorageSync("storageAddress", state.storageAddress)
        },

        // 添加数据到购物车
        setCartList(state, cartList) {
            state.cartList = cartList
            uni.setStorageSync("cartList", state.cartList);
        },

        // 设置token
        setToken(state, token) {
            state.token = token;
        }
    },

    actions: {
        // 获取token 异步
        async fetchToken(store) {
            const [err1, { encryptedData, rawData, iv, signature }] =
                await uni.getUserProfile({
                    desc: "用于给用户提供刚好体验",
                });

            const [err2, { code }] = await uni.login();

            // 拼接参数 获取token
            const tokenParams = {
                encryptedData,
                rawData,
                iv,
                signature,
                code,
            };

            // 发post请求 获取token  点两次按钮原因是因为 后端程序有bug 还没有修复！！！
            // 改为 uni
            const res3 = await uni.$u.post("/users/wxlogin", tokenParams);

            // 获取token
            const { token } = res3.message;

            store.commit("setToken", token);

            return token;

        }
    }
})
export default store